package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.constant.RedisConstant;
import com.hmdp.constant.StatusConstant;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //查詢緩存
        String shopType = stringRedisTemplate.opsForValue().get(RedisConstant.SHOP_TYPE_LIST);
        if (StrUtil.isNotBlank(shopType)) {
            List<ShopType> typeList = JSONUtil.toList(shopType, ShopType.class);
            return Result.ok(typeList);
        }

        //緩存失效，查詢資料庫
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //數據庫沒有,返回失敗
        if (typeList == null || typeList.size() == 0) {
            return Result.fail(StatusConstant.TYPE_NOT_EXIST);
        }
        //添加緩存
      stringRedisTemplate.opsForValue().set(RedisConstant.SHOP_TYPE_LIST, JSONUtil.toJsonStr(typeList));
        //查詢成功，返回數據
        return Result.ok(typeList);
    }
}
